package com.zhongke.cotrun.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zhongke.cotrun.mapper.CompanyInfoMapper;
import com.zhongke.cotrun.mapper.ExpertInfoMapper;
import com.zhongke.cotrun.mapper.RegionMapper;
import com.zhongke.cotrun.mapper.UserInfoMapper;
import com.zhongke.cotrun.model.exception.MyException;
import com.zhongke.cotrun.model.pojo.*;
import com.zhongke.cotrun.model.resultpackage.CodeMsg;
import com.zhongke.cotrun.service.MessageService;
import com.zhongke.cotrun.service.ResearchService;
import com.zhongke.cotrun.service.UserInfoService;
import com.zhongke.cotrun.shiro.sys.shiro.ShiroUtils;
import com.zhongke.cotrun.shiro.web.entity.WebUserEntity;
import com.zhongke.cotrun.shiro.web.entity.WebUserRoleEntity;
import com.zhongke.cotrun.shiro.web.service.WebUserRoleService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Set;

@Service
public class UserInfoServiceImpl implements UserInfoService {

    private final String salt = "KECHAUNGHUI";//盐
    @Autowired
    UserInfoMapper userInfoMapper;
    @Autowired
    MessageService messageService;
    @Autowired
    ExpertInfoMapper expertInfoMapper;
    @Autowired
    RegionMapper regionMapper;
    @Autowired
    CompanyInfoMapper companyInfoMapper;
    @Autowired
    ResearchService researchService;
    @Autowired
    WebUserRoleService webUserRoleService;

    /**
     * 个人注册
     *
     * @param userInfo
     * @return
     * @throws MyException
     */
    @Override
    public boolean useRegistration(UserInfo userInfo) throws MyException {


        String phoneNumber = userInfo.getPhoneNumber();
        String passwd = userInfo.getPasswd() + salt;

//
//        if (!"1".equals(userInfo.getType())) {
//            throw new MyException(CodeMsg.USER_TYPE_ERROR);
//        }
//1查询手机号是否注册
        UserInfo userInfo1 = userInfoMapper.selectUserInfoByphone(phoneNumber);


        if (userInfo1 != null) {
            throw new MyException(CodeMsg.PHONENUMBER_ERROR);
        }
//提交注册信息
        String md5Password = DigestUtils.md5DigestAsHex(passwd.getBytes());
        userInfo.setPasswd(md5Password);

        return userInfoMapper.insertUserInfo(userInfo);
    }


    /**
     * 公司注册
     *
     * @param userInfo
     * @return
     * @throws MyException
     */
    public boolean companyUseRegistration(UserInforCompany userInfo) throws MyException {


        String phoneNumber = userInfo.getPhoneNumber();
        String passwd = userInfo.getPasswd() + salt;
        String companyName = userInfo.getCompanyName();
        //1查询手机号是否注册

        if (!"2".equals(userInfo.getType())) {
            throw new MyException(CodeMsg.USER_TYPE_ERROR);
        }
        UserInfo userInfo1 = userInfo1 = userInfoMapper.selectUserInfoByphoneAndCompanyName(phoneNumber, companyName);
        if (userInfo1 != null) {
            throw new MyException(CodeMsg.PHONEORCOMPANYNAMENUMBER_ERROR);
        }
////提交注册信息
        String md5Password = DigestUtils.md5DigestAsHex(passwd.getBytes());
        userInfo.setPasswd(md5Password);

        return userInfoMapper.insertUserInfoForCompany(userInfo);
    }


    /**
     * 登录
     *
     * @param phoneNumber
     * @param passwd
     * @return
     */
    @Override
    public boolean userLogin(String phoneNumber, String code, String passwd, HttpSession session) throws MyException {
        UserInfo userInfo = userInfoMapper.selectUserInfoByphone(phoneNumber);

        if (userInfo == null) {
            throw new MyException(CodeMsg.ACCOUNT_ERROR);
        }
        if (userInfo.getState() == 2) {
            throw new MyException(CodeMsg.USER_unallowable_ERROR);
        }
        String type = userInfo.getType();

        if (code != null && !" ".equals(code)) {
            if (messageService.verifyCode(code, session)) {
                if ("2".equals(type)) {
                    userInfo = userInfoMapper.selectUserInfoByphoneForCompany(phoneNumber);
                }
                session.setAttribute("USERINFO", userInfo);
                session.setMaxInactiveInterval(1800);
                return true;
            }
            throw new MyException(CodeMsg.MESSAGE_ERROR);
        }

        if (passwd == null || " ".equals(passwd)) {
            throw new MyException(CodeMsg.PWD_ERROR);
        }
        String pwd = userInfo.getPasswd();

        String md5Password = DigestUtils.md5DigestAsHex((passwd + salt).getBytes());

        if (md5Password.equals(pwd)) {
            if ("2".equals(type)) {
                userInfo = userInfoMapper.selectUserInfoByphoneForCompany(phoneNumber);
            }
            session.setAttribute("USERINFO", userInfo);
            session.setMaxInactiveInterval(1800);
            return true;
        } else {
            throw new MyException(CodeMsg.PASSWORD_ERROR);
        }

    }

    /**
     * 修改个人用户信息
     *
     * @param userInfo
     * @return
     */
    @Override
    public boolean updateUserInfo(UserInfo userInfo, HttpSession session) throws MyException {

        String message = userInfo.getMessage();//获取验证码
        //1. 验证码不为空校验验证码
        //手机号修改的时候
        String phoneNumber = userInfo.getPhoneNumber();

        if (phoneNumber != null && !"".equals(phoneNumber)) {
            UserInfo userInfo1 = userInfoMapper.selectUserInfoByphone(phoneNumber);
            if (userInfo1 != null) {
                throw new MyException(CodeMsg.PHONENUMBER_ERROR);
            }
            if (message == null || !messageService.verifyCode(message, session)) {
                throw new MyException(CodeMsg.MESSAGE_ERROR);
            }
            return userInfoMapper.updateUserInfo(userInfo);
        }

        //修改密码
        String passwd = userInfo.getPasswd();
        if (passwd != null && !"".equals(passwd)) {
            if (passwd.length() < 6 || passwd.length() > 8) {
                throw new MyException(CodeMsg.PASSWORDWORD_ERROP);
            }

            String md5Password = DigestUtils.md5DigestAsHex((passwd + salt).getBytes());
            userInfo.setPasswd(md5Password);
            return userInfoMapper.updateUserInfo(userInfo);
        }
        userInfo.setComplete(1);
        return userInfoMapper.updateUserInfo(userInfo);
    }

    /**
     * 修改企业用户信息
     *
     * @param userInfo
     * @return
     * @throws MyException
     */
    @Override
    public boolean updateUserInfoForCompany(UserInforCompany userInfo) throws MyException {
        //1根据公司名查询用户信息
        userInfo.setAuditStatus(0);
        UserInforCompany userInforCompany = userInfoMapper.selectUserInfoByCompanyName(userInfo.getCompanyName());
        Integer id = userInfo.getUserId();
        if (userInforCompany != null) {
            Integer idf = userInforCompany.getUserId();
            if (!idf.equals(id)) {
                throw new MyException(CodeMsg.COMPANCY_ERROP);
            }
            userInfo.setCompanyId(userInforCompany.getCompanyId());
            return companyInfoMapper.updateCompanyInfoByUser(userInfo);
        }
        userInforCompany = userInfoMapper.selectUserInfoFoCompanyById(userInfo.getUserId());
        if (userInforCompany != null && userInforCompany.getCompanyName() != null) {
            userInfo.setCompanyId(userInforCompany.getCompanyId());
            return companyInfoMapper.updateCompanyInfoByUser(userInfo);
        }

        return companyInfoMapper.saveCompanyInfoByUser(userInfo);
    }

    /**
     * 根据id查看个人信息
     *
     * @param userId
     * @return
     */
    @Override
    public UserInfo selectUserInfoByid(Integer userId) {

        return userInfoMapper.selectUserInfoById(userId);

    }

    /**
     * 根据id查看企业基本信息
     *
     * @param userId
     * @return
     */
    @Override
    public UserInforCompany selectUserInfoCompanyById(Integer userId) {
        UserInforCompany userInforCompany = userInfoMapper.selectUserInfoFoCompanyById(userId);
//        if(userInforCompany.getProvince()!=null)
//            userInforCompany.setProvinceName(getRegionName(Integer.valueOf(userInforCompany.getProvince())));
//        if(userInforCompany.getCity()!=null)
//            userInforCompany.setCityName(getRegionName(Integer.valueOf(userInforCompany.getCity())));
        return userInforCompany;
    }

    /**
     * 校验密码
     *
     * @param passwd
     * @param session
     * @return
     */
    @Override
    public boolean verifyPassword(String passwd, HttpSession session) throws MyException {
//        UserInfo userInfo = (UserInfo) session.getAttribute("USERINFO");

        WebUserEntity userInfo = ShiroUtils.getWebUser();

        String md5Password = DigestUtils.md5DigestAsHex((passwd + salt).getBytes());
        if (userInfo == null) {
            throw new MyException(CodeMsg.MUST_LOGIN_ERROP);
        }
        UserInfo lu = userInfoMapper.selectUserInfoById(userInfo.getUserId().intValue());
        if (md5Password.equals(lu.getPasswd())) {
            return true;
        }

        return false;
    }

    /**
     * 校验手机号
     *
     * @param phoneNumber
     * @param session
     * @return
     */

    @Override
    public Boolean verifyPhoneNumber(String phoneNumber, HttpSession session) throws MyException {

//        UserInfo userInfo = (UserInfo) session.getAttribute("USERINFO");

        WebUserEntity userInfo = ShiroUtils.getWebUser();
        if (userInfo == null) {
            throw new MyException(CodeMsg.MUST_LOGIN_ERROP);
        }
        UserInfo lu = userInfoMapper.selectUserInfoById(userInfo.getUserId().intValue());

        if (phoneNumber.equals(lu.getPhoneNumber())) {
            return true;
        }

        return false;
    }

    /**
     * 获取相关的用户信息
     *
     * @param id
     * @return
     */
    @Override
    public UserInforCompany selectUserInfoByIdFilter(Integer id) {
        UserInforCompany uc = userInfoMapper.selectUserInfoFoCompanyByIdFilter(id);
        String province = uc.getProvince();//获取省的code
        String city = uc.getCity();//获取市的code；

        isCity(province, city, uc);
        return uc;
    }

    /**
     * 查询所有的用户信息
     *
     * @param userInforCompany
     * @param pageNumber
     * @param pageSize
     * @return
     */
    @Override
    public PageInfo selectUserInfoAll(UserInforCompany userInforCompany, Integer pageNumber, Integer pageSize) {
        PageHelper.startPage(pageNumber, pageSize);
        List<UserInforCompany> ls = userInfoMapper.selectAllUserInfo(userInforCompany);
        if (ls == null || ls.size() == 0) {
            return new PageInfo(ls);
        }
        for (UserInforCompany u : ls) {
            String province = u.getProvince();
            String city = u.getCity();
            isCity(province, city, u);
        }

        return new PageInfo(ls);
    }

    @Override
    public PageInfo selectAuditUser(UserInfo userInfo, Integer pageNumber, Integer pageSize) {
        PageHelper.startPage(pageNumber, pageSize);
        if (userInfo.getAuditStatus() != null && userInfo.getAuditStatus() == 0) {
            userInfo.setSort("asc");
        } else {
            userInfo.setSort("desc");
        }
        List<UserInfo> list = userInfoMapper.selectAuditUser(userInfo);
        if (list == null || list.size() == 0) {
            return new PageInfo(list);
        }
        for (UserInfo user : list) {
            String province = user.getProvince();
            String city = user.getCity();
            isCity(province, city, user);
        }

        return new PageInfo(list);
    }

    @Override
    public int queryUnApprovalCounts() {
        return userInfoMapper.queryUnApprovalCounts();
    }

    @Override
    public <T> T selectAuditUserInfoById(Long id, Integer approvalType) {
        switch (approvalType) {
            case 1:
                UserInfoExpert userInfoExpert = userInfoMapper.selectUserInfoExpertByExpertId(id);
                if (userInfoExpert == null)
                    return null;
                if (userInfoExpert.getProvince() != null)
                    userInfoExpert.setProvinceName(getRegionName(Integer.valueOf(userInfoExpert.getProvince())));
                if (userInfoExpert.getCity() != null)
                    userInfoExpert.setCityName(getRegionName(Integer.valueOf(userInfoExpert.getCity())));
                if (userInfoExpert.getResearchArea() != null)
                    userInfoExpert.setResearchArea(researchService.selectResearch(userInfoExpert.getResearchArea(), ","));
                userInfoExpert.setPasswd(null);
                return (T) userInfoExpert;
            case 2:
                CompanyInfoVo companyInfo = companyInfoMapper.selectCompanyInfoById(id);
                if (companyInfo == null)
                    return null;
                companyInfo.setProvinceName(getRegionName(companyInfo.getProvince()));
                companyInfo.setCityName(getRegionName(companyInfo.getCity()));
                return (T) companyInfo;
            default:
                return null;
        }
    }

    @Override
    @Transactional
    public boolean approvalPass(Long id, Integer userId, Integer approvalType) {
        String userName = ShiroUtils.getUserName();
        WebUserRoleEntity webUserRoleEntity;
        switch (approvalType) {
            case 1:
                String identify = userInfoMapper.selectIdentity(userId);
                if (identify != null) {
                    if (identify.indexOf("专家") < 0) {
                        identify += "|专家";
                    }
                } else {
                    identify = "专家";
                }
                userInfoMapper.setIdentityForuser(identify, userId);
                webUserRoleEntity = new WebUserRoleEntity(userId.longValue(), 2l); //添加角色
                webUserRoleService.save(webUserRoleEntity);
                return expertInfoMapper.approvalPass(id, userName);  //修改专家审核状态
            case 2:
                webUserRoleEntity = new WebUserRoleEntity(userId.longValue(), 3l);
                webUserRoleService.save(webUserRoleEntity); //添加机构角色权限
                webUserRoleService.remove(new QueryWrapper<WebUserRoleEntity>().eq("role_id", 1).eq("user_id", userId));  //删除个人角色权限
                userInfoMapper.updateUserTypeByCompanyId(id);   //修改账号基本类型
                return companyInfoMapper.approvalPass(id, userName); //修改审核状态
            default:
                return false;
        }
    }

    @Override
    public boolean approvalReject(Long id, Integer approvalType, String auditOpinion) {
        String userName = ShiroUtils.getUserName();
        switch (approvalType) {
            case 1:
                return expertInfoMapper.approvalRejected(id, userName, auditOpinion);
            case 2:
                return companyInfoMapper.approvalRejected(id, userName, auditOpinion);
            default:
                return false;
        }
    }


    /**
     * 城市转换
     *
     * @param province
     * @param city
     * @param uc
     */
    public void isCity(String province, String city, UserInfo uc) {
        Region region;
        if (StringUtils.isNotEmpty(province)) {
            region = regionMapper.selectByPrimaryKey(Integer.valueOf(province));
            uc.setProvinceName(region.getName());
        }

        if (StringUtils.isNotEmpty(city)) {
            region = regionMapper.selectByPrimaryKey(Integer.valueOf(city));
            uc.setCityName(region.getName());
        }

    }

    public String getRegionName(Integer regionId) {
        if (regionId != null)
            return regionMapper.selectByPrimaryKey(Integer.valueOf(regionId)).getName();
        return null;
    }

    /**
     * 批量修改审核状态
     *
     * @param userIds
     * @param state
     * @return
     */

    @Override
    public Boolean upUserState(Set<Integer> userIds, Integer state) {

        return userInfoMapper.updateUserState(userIds, state);
    }

    /**
     * 修改用户身份信息
     *
     * @param enditiy
     * @param userId
     * @return
     */
    @Override
    public Boolean addUserEnditiy(String enditiy, Integer userId) {

        String a = userInfoMapper.selectIdentity(userId);

        if (a != null) {
            a += "," + enditiy;
        } else {
            a = enditiy;
        }

        return userInfoMapper.updateUserIdentity(a, userId);
    }
}
